package com.example.downloadmanagerdemo;

import java.util.ArrayList;
import java.util.List;

import com.example.downloadmanagerdemo.adapter.DownloadAdapter;
import com.example.downloadmanagerdemo.download.DownloadInfo;
import com.example.downloadmanagerdemo.download.DownloadManager;
import com.example.downloadmanagerdemo.download.DownloadRecordHelper;
import com.example.downloadmanagerdemo.download.DownloadStatus;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;

public class MainActivity extends Activity {
	private ListView mListView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		DownloadRecordHelper.getInstance().init(getApplication());
		setContentView(R.layout.activity_main);
		initViews();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private void initViews() {
		List<DownloadInfo> infos = new ArrayList<DownloadInfo>();
		for (int i = 0; i < UrlProvider.DOWNLOAD_URLS.length; i++) {
			DownloadInfo info = new DownloadInfo();
			info.setDownloadUrl(UrlProvider.DOWNLOAD_URLS[i]);
			info.setPackageName("com.download.demodemo" + i);
			info.setId(i);
			infos.add(info);
		}
		refreshStatus(infos);
		DownloadAdapter adapter = new DownloadAdapter(infos, this, DownloadManager.getInstance(this));
		mListView = (ListView) findViewById(R.id.listView1);
		mListView.setAdapter(adapter);
	}

	private void refreshStatus(List<DownloadInfo> infos) {
		for (DownloadInfo info : infos) {
			if (DownloadRecordHelper.getInstance().isFinished(info.getPackageName())) {
				info.setDownloadState(DownloadStatus.STATUS_SUCCESS);
			}
			long saveSize = DownloadRecordHelper.getInstance().readSavedSize(info.getPackageName());
			long size = DownloadRecordHelper.getInstance().readSize(info.getPackageName());
			if (saveSize > 0 && size > 0) {
				info.setDownloadedSize(saveSize);
				info.setProgress((int) (saveSize * 100 / size));
				info.setDownloadState(DownloadStatus.STATUS_PAUSE);
			}
		}
	}

	@Override
	public void onDestroy() {
		DownloadManager.getInstance(this).pauseAll();
		super.onDestroy();
	}
}
